package com.example.blue_classic_plus.blueconnect;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;

import com.example.blue_classic_plus.EntityUtils;
import com.example.blue_classic_plus.SinkEntity;
import com.example.blue_classic_plus.StatusCode;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import io.flutter.plugin.common.EventChannel;

public class ServerThread extends Thread {

    ///服务端开启成功
    public boolean listenSuccess = true;

    public  boolean listenError = false;

    private final BluetoothServerSocket serverSocket;
    private List<BluetoothSocket> clientSocketList;

    Handler handler;


    public ServerThread(String name, UUID uuid,Handler handler) {
        this.handler = handler;
        BluetoothServerSocket tmp = null;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        try {
            /// 获取 BluetoothServerSocket
            tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(name, uuid);
        } catch (Exception e) {
            System.out.println("ServerThread:" + e);
        }
        serverSocket = tmp;
        clientSocketList = new ArrayList<>();
        handleServerStartSuccess(listenSuccess);
    }

    public void run() {
        BluetoothSocket clientSocket;
        /// 监听连接请求
        while (true) {
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                //System.out.println("Socket's accept() method failed：" + e);
                listenError = true;
                handleServerListenError();
                break;
            }

            if (clientSocket != null) {
                ///获取连接过来的设备信息
                handleClientConnected(clientSocket);

                // 执行数据传输逻辑
                //sendData(clientSocket, "client success");
                handleReceiveMessages(clientSocket);
            }
        }
    }

    ///实时监听客户端的消息
    private void handleReceiveMessages(BluetoothSocket clientSocket) {
        Thread receiveThread = new Thread(() -> {
            byte[] buffer = new byte[1024];
            int bytes;

            while (clientSocket.isConnected()) {
                try {
                    // 读取客户端发送的消息
                    bytes = clientSocket.getInputStream().read(buffer);
                    if (bytes > 0) {
                        String message = new String(buffer, 0, bytes);
                        processData(clientSocket, message);
                    }
                } catch (IOException e) {
                    ///不是监听出错的话，才说明是客户端发起的断开。
                    if (!listenError) {
                        handleClientDisconnected(clientSocket);
                    }

                }
            }
        });
        receiveThread.start();
    }

    ///服务端开启成功或失败
    private void handleServerStartSuccess(boolean startSuccess) {
        listenSuccess = startSuccess;
        Map<String, Object> map = new HashMap<>();
        map.put("code", startSuccess ? StatusCode.serverStartSuccess : StatusCode.serverStartFail);
        sinkServerStatusToFlutter(map);
    }

    ///服务端出错连接断开了
    private void handleServerListenError() {
        listenSuccess = false;
        //System.out.println("服务端错误了");

        Map<String, Object> map = new HashMap<>();
        map.put("code", StatusCode.serverListenError);
        sinkServerStatusToFlutter(map);
    }

    ///客户端连接成功了
    private void handleClientConnected(BluetoothSocket clientSocket) {
        clientSocketList.add(clientSocket);
        BluetoothDevice clientDevice = clientSocket.getRemoteDevice();
        //System.out.println("客户端<" + clientDevice.getName() + ">连接成功 " + clientDevice.getAddress());

        Map<String, Object> map = new HashMap<>();
        map.put("code", StatusCode.serverRecvClientConnected);
        map.put("name",clientDevice.getName());
        map.put("address",clientDevice.getAddress());
        sinkServerStatusToFlutter(map);

    }

    ///客户端的连接断开了
    private void handleClientDisconnected(BluetoothSocket clientSocket) {
        clientSocketList.remove(clientSocket);
        try {
            clientSocket.close();
        } catch (IOException e) {
            //System.out.println("clientSocket.close() error " + e);
        }
        BluetoothDevice clientDevice = clientSocket.getRemoteDevice();
        //System.out.println("客户端<" + clientDevice.getName() + ">连接断开 " + clientDevice.getAddress());

        Map<String, Object> map = new HashMap<>();
        map.put("code", StatusCode.serverRecvClientDisconnected);
        map.put("name",clientDevice.getName());
        map.put("address",clientDevice.getAddress());
        sinkServerStatusToFlutter(map);
    }

    ///主动取消了
    public void cancel() {
        ///关闭server
        try {
            serverSocket.close();
        } catch (IOException e) {
            System.out.println("ServerThread cancel error:" + e);
        }

        ///关闭所有的client
        for (BluetoothSocket clientSocket : clientSocketList) {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.out.println("ServerThread client cancel error:" + e);
            }
        }
    }

    ///收到客户端的消息
    private void processData(BluetoothSocket clientSocket, String message) {
        BluetoothDevice clientDevice = clientSocket.getRemoteDevice();
        System.out.println("来自<" + clientDevice.getName() + ">的消息:" + message);
    }

    ///广播消息
    public void broadcastMessage(String msg) {
        for (BluetoothSocket socket : clientSocketList) {
            sendData(socket, msg);
        }
    }

    ///发送消息
    public void sendData(BluetoothSocket socket, String data) {
        Thread sendThread = new Thread(() -> {
            try {
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(data.getBytes());
                outputStream.flush();
            } catch (IOException e) {
                System.out.println("消息发送失败:" + data);
            }
        });
        sendThread.start();
    }

    ///把服务端的状态告诉flutter
    private void sinkServerStatusToFlutter(Map<String, Object> map) {
        Message message = this.handler.obtainMessage(0,map);
        this.handler.sendMessage(message);
    }
}


